package com.gz.seckill.config;

import com.gz.seckill.service.UserService;
import com.gz.seckill.pojo.User;
import com.gz.seckill.util.CookieUtil;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * UserArgumentResolver: 自定义的一个解析器
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    //装配UserService
    @Resource
    private UserService userService;

    //判断你当前要解析的参数类型是不是你需要的?
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //获取参数是不是user类型
        Class<?> aClass = parameter.getParameterType();
        //如果为t, 就执行resolveArgument
        return aClass == User.class;
    }

    //如果上面supportsParameter,返回T,就执行下面的resolveArgument方法
    //到底怎么解析，是由程序员根据业务来编写
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        // HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        // HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        //
        // String ticket = CookieUtil.getCookieValue(request, "userTicket");
        // if (!StringUtils.hasText(ticket)) {
        //     return null;
        // }
        // //从Redis来获取用户
        // User user = userService.getUserByCookie(ticket, request, response);
        //
        // return user;

        //这里虽然只有一个UserContext.getUser()操作,但是，
        //在AccessLimitInterceptor中，它在判断每个方法是否有@AccessLimit注解前，
        //用了AccessLimitInterceptor中的getUser()实现了以上获得cookie和用户的操作
        //也就是AccessLimitInterceptor不仅是为了实现@AccessLimit注解功能的，
        //它还将获得cookie和获得用户的功能包括在里面了，
        // 并且在UserContext中用了ThreadLocal实现每个用户的操作在它独立的线程中,保证线程安全
       return UserContext.getUser();
    }
}
